package com.javector.soashopper.ebay;

import java.util.ArrayList;
import java.util.List;

import com.javector.soashopper.Category;
import com.javector.soashopper.Offer;
import com.javector.soashopper.Price;
import com.javector.soashopper.ShopperImp;
import com.javector.util.TypeConverter;

import ebay.apis.eblbasecomponents.DetailLevelCodeType;
import ebay.apis.eblbasecomponents.GetSearchResultsRequestType;
import ebay.apis.eblbasecomponents.GetSearchResultsResponseType;
import ebay.apis.eblbasecomponents.PriceRangeFilterType;
import ebay.apis.eblbasecomponents.SearchResultItemType;

public class SOAShopperEBayBinding extends ShopperImp {

	@Override
	public List<Offer> offerSearch(String keywords, Category category, Price lowprice, Price highprice) {
	    TypeConverter tc = new TypeConverter();
	    GetSearchResultsRequestType searchResultsRequest = new GetSearchResultsRequestType();
	    EBayShopperImp.configureEBayRequestType(searchResultsRequest, "GetSearchResults");
	    List<DetailLevelCodeType> details = searchResultsRequest.getDetailLevel();
	    details.add(DetailLevelCodeType.RETURN_ALL);
	    if (category != null) {
	      EBayCategory eBayCategory = tc.toEBayCategory(category);
	      searchResultsRequest.setCategoryID(eBayCategory.getCategoryId());
	    }
	    searchResultsRequest.setQuery(keywords);
	    if (lowprice != null || highprice != null) {
	      PriceRangeFilterType prf = new PriceRangeFilterType();
	      if (lowprice != null) {
	        prf.setMinPrice(tc.toAmountType(lowprice));
	      }
	      if (highprice != null) {
	        prf.setMaxPrice(tc.toAmountType(highprice));
	      }
	      searchResultsRequest.setPriceRangeFilter(prf);
	    }
	    GetSearchResultsResponseType searchResultsResponse = null;
	    try {
	      searchResultsResponse = EBayShopperImp.getPort().getSearchResults(searchResultsRequest);
	    } catch (Exception e) {
	      throw new RuntimeException(
	          "SOAShopperEBayBinding.offerSearch() threw an Exception", e);
	    }
	    List<SearchResultItemType> searchResultList = searchResultsResponse
	        .getSearchResultItemArray().getSearchResultItem();
	    List<Offer> retVal = new ArrayList<Offer>();
	    for (SearchResultItemType srit : searchResultList) {
	      retVal.add(new Offer(new EBayOfferImp(srit.getItem())));
	    }
	    return retVal;
	}

}
